﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cdhpy.Util
{
    public sealed class Validate
    {
        /// <summary>
        /// 实体类中是否每个值都为NULL
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>true: 全为NULL</returns>
        public static bool IsEntityFieldsAllNull(object obj)
        {
            if (obj == null)
                return true;
            try
            {
                System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties
                         (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

                return properties.All(y => y.GetValue(obj, null) == null);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 过滤Sql中的特殊字符防止sql注入(简易过滤, 不推荐使用)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SqlFileter(string str)
        {
            if (String.IsNullOrEmpty(str))
                return str;
            else
                return str.Replace(";", "").Replace("(", "").Replace(")", "")
                    .Replace(",", "").Replace("/", "").Replace(@"\", "").Replace("'", "").Replace("\"", "");
        }

        /// <summary>
        /// SqlParameters null值处理
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object SqlParamFormat(object obj)
        {
            if (obj == null)
                return DBNull.Value;
            return obj;
        }

        /// <summary>
        /// 文件路径是否存在
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="createIfNotExist">若不在是否创建</param>
        /// <returns>true：确定存在  false：不存在或创建失败</returns>
        public static bool IsDirExists(string filePath, bool createIfNotExist = true)
        {
            if (!System.IO.Directory.Exists(filePath))
            {
                if(createIfNotExist)
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(filePath); //创建新路径
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
                
            }
            else
            {
                return true;
            }
        }
    }
}
